package com.gift.service.Impl;

import com.gift.common.PaGing;
import com.gift.common.ServerResponse;
import com.gift.common.TimeHandler;
import com.gift.dao.*;
import com.gift.pojo.*;
import com.gift.service.DealTableService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/12.
 */

@Service("dealTableService")
@Transactional
public class DealTableServiceImpl  implements DealTableService {


    @Resource
    DealTableMapper dealTableMapper;
    @Resource
    GamesMapper gamesMapper;
    @Resource
    AccByDeaMapper accByDeaMapper;
    @Resource
    GameAccountMapper gameAccountMapper;
    @Resource
    BankCardMapper bankCardMapper;
    @Resource
    BankByDealtMapper bankByDealtMapper;

    //没用到
    @Override
    public List getAllOfToDayBypr() {
        //八点到下午4点是早班，16点到零点是中班。零点到第二天8点是晚班
        LocalDateTime workTimeBegin = LocalDateTime.MIN.plusHours(8);
        LocalDateTime workTimeEnd = workTimeBegin.plusHours(24);
        //查出在这个时间段内的交易
        return dealTableMapper.getWorkTime(workTimeBegin,workTimeEnd);
    }

    //先验证今天的班次有不有，班次有，这个游戏游戏有不有
    public DealTable seekShift( Map<String, Object> map){
        //八点到下午4点是早班，16点到零点是中班。零点到第二天8点是晚班
        LocalDate toDay = LocalDate.now();
        int nowShift =TimeHandler.getShift();


        DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime toDayBegin = LocalDateTime.parse(toDay.toString()+" 00:00:00", sf);

        LocalDateTime workTimeBegin = toDayBegin.plusHours(8);
        LocalDateTime workTimeEnd = workTimeBegin.plusHours(24);

        if(nowShift == 2){
            workTimeBegin = toDayBegin;
            workTimeEnd = toDayBegin.plusHours(8);
        }

        map.put("workTimeBegin",workTimeBegin);
        map.put("workTimeEnd",workTimeEnd);
        return dealTableMapper.seekShift(map);
    }

    //验证今日今班次中，此银行卡有不有发生流水
    public BankByDealt seekBankLSofShift( Map<String, Object> map){
        //八点到下午4点是早班，16点到零点是中班。零点到第二天8点是晚班
        //八点到下午4点是早班，16点到零点是中班。零点到第二天8点是晚班
        LocalDate toDay = LocalDate.now();
        int nowShift =TimeHandler.getShift();

        DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime toDayBegin = LocalDateTime.parse(toDay.toString()+" 00:00:00", sf);

        LocalDateTime workTimeBegin = toDayBegin.plusHours(8);
        LocalDateTime workTimeEnd = workTimeBegin.plusHours(24);

        if(nowShift == 2){
            workTimeBegin = toDayBegin;
            workTimeEnd = toDayBegin.plusHours(8);
        }
        map.put("workTimeBegin",workTimeBegin);
        map.put("workTimeEnd",workTimeEnd);
        return bankByDealtMapper.selectByDid(map);
    }

//卖分
    @Override
    public ServerResponse sellingScore(DealTable selDeal, Map<String, String> map) {
        Map<String, Object> shiftMap = new HashMap<>();
        shiftMap.put("shift",selDeal.getShift());
        shiftMap.put("gid",map.get("gid"));
        DealTable resSeekShift=seekShift(shiftMap);
        //在今天的一个班次和游戏交易没找到，就新建,并新建账号卖分、银行卡余额更新和账号余额更新
        if(resSeekShift == null){
            Games games=gamesMapper.selectByPrimaryKey(selDeal.getGid());
            String gameNmae=games.getGname();
//            BigDecimal bili = games.getProportion();
//            selDeal.setProportion(bili);
            selDeal.setGname(gameNmae);
            selDeal.setBuyscore(new BigDecimal("0"));
            //新建新并返回主键
            int res0=dealTableMapper.insertSelective(selDeal);
            int did =selDeal.getDid();
            //存关联的游戏账号流水
            AccByDea accByDea = new AccByDea();
            accByDea.setDid(did);
            accByDea.setGid(selDeal.getGid());
            accByDea.setGname(gameNmae);
            int aid =Integer.valueOf(map.get("aid"));
            accByDea.setAid(aid);
            GameAccount account=gameAccountMapper.selectByPrimaryKey(aid);
            //更新账号余额
            account.setInitialscore(account.getInitialscore().subtract(selDeal.getSellingscore()).subtract(selDeal.getGiftscore()));
            int res2=gameAccountMapper.updateByPrimaryKeySelective(account);
            //先改变游戏账号现有分数，流水的现有分数才是准确的
            String accountnum=account.getAccountnum();
            accByDea.setAccountnum(accountnum);
            accByDea.setInitialscore(account.getInitialscore());
            accByDea.setSendscore(selDeal.getSellingscore().add(selDeal.getGiftscore()));
            accByDea.setShift(selDeal.getShift());
            accByDea.setGetscore(new BigDecimal("0"));
            accByDea.setHandlerid(Integer.valueOf(map.get("handlerid")));
            accByDea.setHandlers(map.get("handlers"));
            int res1=accByDeaMapper.insertSelective(accByDea);

            //更新银行卡余额,比例是多少分等于一元
//            BigDecimal getMoney=selDeal.getSellingscore().divide(games.getProportion(),2, BigDecimal.ROUND_DOWN);
            int bid=Integer.valueOf(map.get("bid"));
            BankCard bankCard=bankCardMapper.selectByPrimaryKey(bid);
//            bankCard.setInitialnum(bankCard.getInitialnum().add(getMoney));
            int res3=bankCardMapper.updateByPrimaryKeySelective(bankCard);
            //更新银行卡流水
            BankByDealt bbd = new BankByDealt();
            bbd.setDid(did);
            bbd.setBid(bid);
            bbd.setAlias(bankCard.getAlias());
            bbd.setGname(gameNmae);
            bbd.setGid(selDeal.getGid());
//            bbd.setIncome(getMoney);
            bbd.setExpend(new BigDecimal("0"));
            bbd.setPoundage(new BigDecimal("0"));
            bbd.setShift(selDeal.getShift());
            bbd.setHandlerid(selDeal.getHandlerid());
            bbd.setHandlers(selDeal.getHandlers());
            int res4 = bankByDealtMapper.insertSelective(bbd);
            if(res1 != 1 || res2 != 1 || res3 != 1 || res4 != 1){
               return ServerResponse.createByErrorMessage("卖分发生错误");
            }

        }else{
            //找到了就将卖分叠加并更新,并更新账号卖分、银行卡余额更新和账号余额更新
            resSeekShift.setSellingscore(resSeekShift.getSellingscore().add(selDeal.getSellingscore()));
            resSeekShift.setGiftscore(resSeekShift.getGiftscore().add(selDeal.getGiftscore()));
            resSeekShift.setHelpscore(resSeekShift.getHelpscore().add(selDeal.getHelpscore()));
            resSeekShift.setHelpeduid(selDeal.getHelpeduid());
            resSeekShift.setRemark(resSeekShift.getRemark()+selDeal.getRemark());
            int res1 = dealTableMapper.updateByPrimaryKey(resSeekShift);
            //根据流水id找账号关联流水，看账号是否一致，不一致新建，一致更新
            int aid =Integer.valueOf(map.get("aid"));
            GameAccount account=gameAccountMapper.selectByPrimaryKey(aid);
            AccByDea accByDea=accByDeaMapper.selectByDid(resSeekShift.getDid(),aid);
            Games games=gamesMapper.selectByPrimaryKey(selDeal.getGid());
            //更新账号余额
            account.setInitialscore(account.getInitialscore().subtract(selDeal.getSellingscore()).subtract(selDeal.getGiftscore()));
            int res3=gameAccountMapper.updateByPrimaryKeySelective(account);
            int res2 = 0;
            //同一游戏，不是同一账号
            if(accByDea == null){
                AccByDea newAccByDea = new AccByDea();
                newAccByDea.setDid(resSeekShift.getDid());
                String gameNmae=games.getGname();
                newAccByDea.setGid(selDeal.getGid());
                newAccByDea.setGname(gameNmae);
                newAccByDea.setAid(aid);
                String accountnum=account.getAccountnum();
                newAccByDea.setAccountnum(accountnum);
                newAccByDea.setInitialscore(account.getInitialscore());
                newAccByDea.setSendscore(selDeal.getSellingscore().add(selDeal.getGiftscore()));
                newAccByDea.setShift(selDeal.getShift());
                newAccByDea.setHandlerid(Integer.valueOf(map.get("handlerid")));
                newAccByDea.setHandlers(map.get("handlers"));
                res2=accByDeaMapper.insertSelective(newAccByDea);
            }else{
                //同一游戏，也是同一账号
                accByDea.setInitialscore(account.getInitialscore());
                accByDea.setSendscore(accByDea.getSendscore().add(selDeal.getSellingscore()).add(selDeal.getGiftscore())                                                   );
                res2=accByDeaMapper.updateByPrimaryKey(accByDea);
            }

            //更新银行卡余额,比例是多少分等于一元
//            BigDecimal getMoney=selDeal.getSellingscore().divide(games.getProportion(),2, BigDecimal.ROUND_DOWN);
            int bid=Integer.valueOf(map.get("bid"));
            BankCard bankCard=bankCardMapper.selectByPrimaryKey(bid);
//            bankCard.setInitialnum(bankCard.getInitialnum().add(getMoney));
            int res4=bankCardMapper.updateByPrimaryKeySelective(bankCard);
            //更新银行卡流水
            Map<String, Object> mapLS = new HashMap<>();
            mapLS.put("shift",selDeal.getShift());
            mapLS.put("did",resSeekShift.getDid());
            BankByDealt todayToShiftToBankLS=seekBankLSofShift(mapLS);
//            todayToShiftToBankLS.setIncome(todayToShiftToBankLS.getIncome().add(getMoney));
            int res5 = bankByDealtMapper.updateByPrimaryKey(todayToShiftToBankLS);
            if(res1 != 1 || res2 != 1 || res3 != 1 || res4 != 1 || res5 != 1){
                return ServerResponse.createByErrorMessage("卖分发生错误");
            }
        }


        return ServerResponse.createBySuccessMessage("交易记录成功");
    }

    //卖分2
    @Override
    public ServerResponse sellingScore2( Map<String, String> map) {
        int shift = TimeHandler.getShift();
        List<BankCard> bankList=bankCardMapper.getAll();
        for(BankCard b:bankList){
            String bkey = b.getBid()+"sellingscore";
            if(map.get("bkey") != null && map.get("bkey") != ""){
                //卖出多少钱
                String sellingscore=map.get("bkey");
                BigDecimal getMoney = new BigDecimal(sellingscore);
                BankCard bankCard=bankCardMapper.selectByPrimaryKey(b.getBid());
                Games game=gamesMapper.selectByPrimaryKey(Integer.valueOf(map.get("Gid")));
                //找出游戏的卖分比例
                BigDecimal sellAcc= game.getSellProportion();
                BigDecimal sellingFen = getMoney.multiply(sellAcc);
            }
        }
        return null;
    }

    //买分
    @Override
    public ServerResponse buyScore(DealTable buyDeal, Map<String, String> map) {
        Map<String, Object> shiftMap = new HashMap<>();
        shiftMap.put("shift",buyDeal.getShift());
        shiftMap.put("gid",map.get("gid"));
        DealTable resSeekShift=seekShift(shiftMap);
        //在今天的一个班次和游戏交易没找到，就新建,并新建账号卖分、银行卡余额更新和账号余额更新
        if(resSeekShift == null){
            Games games=gamesMapper.selectByPrimaryKey(buyDeal.getGid());
            String gameNmae=games.getGname();
//            BigDecimal bili = games.getProportion();
//            buyDeal.setProportion(bili);
            buyDeal.setGname(gameNmae);
            buyDeal.setSellingscore(new BigDecimal("0"));
            //新建新并返回主键
            int re0 =dealTableMapper.insertSelective(buyDeal);
            int did = buyDeal.getDid();
            //更新账号余额
            int aid =Integer.valueOf(map.get("aid"));
            GameAccount account=gameAccountMapper.selectByPrimaryKey(aid);
            account.setInitialscore(account.getInitialscore().add(buyDeal.getBuyscore()));
            int res2=gameAccountMapper.updateByPrimaryKeySelective(account);
            //存关联的游戏账号流水
            AccByDea accByDea = new AccByDea();
            accByDea.setDid(did);
            accByDea.setGid(buyDeal.getGid());
            accByDea.setGname(gameNmae);
            accByDea.setAid(aid);
            String accountnum=account.getAccountnum();
            accByDea.setAccountnum(accountnum);
            accByDea.setInitialscore(account.getInitialscore());
            accByDea.setGetscore(buyDeal.getBuyscore());
            accByDea.setSendscore(new BigDecimal("0"));
            accByDea.setShift(buyDeal.getShift());
            accByDea.setHandlerid(Integer.valueOf(map.get("handlerid")));
            accByDea.setHandlers(map.get("handlers"));
            int res1=accByDeaMapper.insertSelective(accByDea);

            //更新银行卡余额,比例是多少分等于一元
//            BigDecimal sendMoney=buyDeal.getBuyscore().divide(games.getProportion(),2, BigDecimal.ROUND_DOWN);
            int bid=Integer.valueOf(map.get("bid"));
            BankCard bankCard=bankCardMapper.selectByPrimaryKey(bid);
//            bankCard.setInitialnum(bankCard.getInitialnum().subtract(sendMoney).subtract(new BigDecimal(map.get("poundage"))));
            int res3=bankCardMapper.updateByPrimaryKeySelective(bankCard);
            //更新银行卡流水
            BankByDealt bbd = new BankByDealt();
            bbd.setDid(did);
            bbd.setBid(bid);
            bbd.setAlias(bankCard.getAlias());
            bbd.setGname(gameNmae);
            bbd.setGid(buyDeal.getGid());
//            bbd.setExpend(sendMoney);
            bbd.setPoundage(new BigDecimal(map.get("poundage")));
            bbd.setIncome(new BigDecimal("0"));
            bbd.setShift(buyDeal.getShift());
            bbd.setHandlerid(buyDeal.getHandlerid());
            bbd.setHandlers(buyDeal.getHandlers());
            int res4 = bankByDealtMapper.insertSelective(bbd);
            if(res1 != 1 || res2 != 1 || res3 != 1 || res4 != 1){
                return ServerResponse.createByErrorMessage("买分发生错误");
            }
            return ServerResponse.createBySuccessMessage("交易记录成功");
        }
        //找到了就将买分叠加并更新,并更新账号买分、银行卡余额更新和账号余额更新
        resSeekShift.setBuyscore(resSeekShift.getBuyscore().add(buyDeal.getBuyscore()));
        resSeekShift.setRemark(resSeekShift.getRemark()+buyDeal.getRemark());
        int res1 = dealTableMapper.updateByPrimaryKey(resSeekShift);
        //根据流水id找账号关联流水，看账号是否一致，不一致新建，一致更新
        int aid =Integer.valueOf(map.get("aid"));
        GameAccount account=gameAccountMapper.selectByPrimaryKey(aid);
        AccByDea accByDea=accByDeaMapper.selectByDid(resSeekShift.getDid(),aid);
        Games games=gamesMapper.selectByPrimaryKey(buyDeal.getGid());
        int res2 = 0;
        //更新账号余额
        account.setInitialscore(account.getInitialscore().add(buyDeal.getBuyscore()));
        int res3=gameAccountMapper.updateByPrimaryKeySelective(account);
        //同一游戏，不是同一账号
        if(accByDea == null){
            AccByDea newAccByDea = new AccByDea();
            newAccByDea.setDid(resSeekShift.getDid());
            String gameNmae=games.getGname();
            newAccByDea.setGid(buyDeal.getGid());
            newAccByDea.setGname(gameNmae);
            newAccByDea.setAid(aid);
            String accountnum=account.getAccountnum();
            newAccByDea.setAccountnum(accountnum);
            newAccByDea.setInitialscore(account.getInitialscore());
            newAccByDea.setGetscore(buyDeal.getBuyscore());
            newAccByDea.setInitialscore(account.getInitialscore());
            newAccByDea.setShift(buyDeal.getShift());
            newAccByDea.setHandlerid(Integer.valueOf(map.get("handlerid")));
            newAccByDea.setHandlers(map.get("handlers"));
            res2=accByDeaMapper.insertSelective(newAccByDea);
        }else{
            //同一游戏，也是同一账号
            accByDea.setInitialscore(account.getInitialscore());
            accByDea.setGetscore(accByDea.getGetscore().add(buyDeal.getBuyscore()));
            res2=accByDeaMapper.updateByPrimaryKey(accByDea);
        }
        //更新银行卡余额,比例是多少分等于一元
//        BigDecimal sendMoney=buyDeal.getBuyscore().divide(games.getProportion(),2, BigDecimal.ROUND_DOWN);
        int bid=Integer.valueOf(map.get("bid"));
        BankCard bankCard=bankCardMapper.selectByPrimaryKey(bid);
//        bankCard.setInitialnum(bankCard.getInitialnum().subtract(sendMoney).subtract(new BigDecimal(map.get("poundage"))));
        int res4=bankCardMapper.updateByPrimaryKeySelective(bankCard);
        //更新银行卡流水
        Map<String, Object> mapLS = new HashMap<>();
        mapLS.put("shift",buyDeal.getShift());
        mapLS.put("did",resSeekShift.getDid());
        BankByDealt todayToShiftToBankLS=seekBankLSofShift(mapLS);
        todayToShiftToBankLS.setPoundage(todayToShiftToBankLS.getPoundage().add(new BigDecimal(map.get("poundage"))));
//        todayToShiftToBankLS.setExpend(todayToShiftToBankLS.getExpend().add(sendMoney));
        int res5 = bankByDealtMapper.updateByPrimaryKey(todayToShiftToBankLS);
        if(res1 != 1 || res2 != 1 || res3 != 1 || res4 != 1 || res5 != 1){
            return ServerResponse.createByErrorMessage("买分发生错误");
        }

        return ServerResponse.createBySuccessMessage("交易记录成功");
    }



}
